package com.sonicboom.nurun;

import com.bazaarvoice.dropwizard.assets.ConfiguredAssetsBundle;
import com.sonicboom.nurun.client.AxicomClient;
import com.sonicboom.nurun.client.WeChatClient;
import com.sonicboom.nurun.dao.IncentiveDAO;
import com.sonicboom.nurun.resource.IncentiveResource;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.db.DataSourceFactory;
import io.dropwizard.jdbi.DBIFactory;
import io.dropwizard.migrations.MigrationsBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.skife.jdbi.v2.DBI;

public class App extends Application<AppConfig> {
    public static void main(String[] args) throws Exception {
        new App().run(args);
    }

    @Override
    public void initialize(Bootstrap<AppConfig> bootstrap) {

        bootstrap.addBundle(new ConfiguredAssetsBundle("/assets/", "/view/"));

        bootstrap.addBundle(new MigrationsBundle<AppConfig>() {
            @Override
            public DataSourceFactory getDataSourceFactory(AppConfig configuration) {
                return configuration.getDataSourceFactory();
            }
        });

    }

    @Override
    public void run(AppConfig config, Environment environment) throws Exception {
        DBIFactory factory = new DBIFactory();
        DBI jdbi = factory.build(environment, config.getDataSourceFactory(), "mysql");
        final WeChatClient weChatClient = new WeChatClient(config.getWechatUrl());
        final AxicomClient axicomClient = new AxicomClient(config.getSourceId(), config.getAxicomAddress());
        final IncentiveDAO incentiveDAO = jdbi.onDemand(IncentiveDAO.class);

        IncentiveResource incentiveResource = new IncentiveResource(weChatClient, axicomClient, incentiveDAO);

        environment.jersey().register(incentiveResource);
    }
}
